package ru.kest.babymonitor.service.audio;

import android.util.Log;
import ru.kest.babymonitor.Settings;

/**
 * Class played audio stream from AudioPlayer
 */
public class AudioAnalyzer implements Runnable {

    private static String TAG = "IPCamBabyMonitorService";
    private Settings settings = Settings.getInstance();
    private AudioQueue audioQueue = AudioQueue.getInstance();

    private static final int SLEEP_TIME = 500;

    private int latencyCounter = settings.getLatency();
    private long lastTime = System.currentTimeMillis();


    @Override
    public void run() {

        try {
            while (true) {
                while (settings.isAlarmOn()) {
                    short[] pack = audioQueue.getDataForAnalysis();
                    int SOUND_MAX_VALUE = settings.getSoundMaxValue() * settings.getSoundMultiplier();

                    for (short sh : pack) {
                        if (Math.abs(sh) > SOUND_MAX_VALUE) {
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - lastTime < settings.getSoundTimeout()) {
                                if (--latencyCounter <=0) {
                                    AlarmPlayer.getInstance().startAlarmSound();
                                    latencyCounter = settings.getLatency();
                                    Log.d(TAG, "AudioAnalyzer: Notify!");
                                }
//                                Log.d(TAG, "AudioAnalyzer: latencyCounter: " + latencyCounter);
                            } else {
                                latencyCounter = settings.getLatency();
//                                Log.d(TAG, "AudioAnalyzer: timeout too big : " + (currentTime - lastTime));
                            }
                            lastTime = currentTime;
                            break;
                        }
                    }
                }
                Thread.sleep(SLEEP_TIME);
            }
        } catch (InterruptedException e) {
            Log.e(TAG, "AudioAnalyzer is interupted");
        }

    }


}
